import { NSelect, SelectOption } from 'naive-ui'
import { defineComponent, nextTick, ref, h } from 'vue'

const ShowOrSelect = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array],
    options: Array<SelectOption>,
    tag: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const isEdit = ref(false)
    const selectRef = ref(null)
    const selectValue = ref(props.value)
    function handleOnClick() {
      if (!isEdit.value) {
        isEdit.value = true
        nextTick(() => {
          selectRef.value.focus()
        })
      }
    }
    function handleChange() {
      props.onUpdateValue(selectValue.value)
      isEdit.value = false
    }
    return () =>
      h(
        'div',
        {
          onClick: handleOnClick,
          style: 'min-width:30px;height:23px'
        },
        isEdit.value
          ? h(
              NSelect,
              {
                ref: selectRef,
                value: selectValue.value,
                size: 'tiny',
                options: props.options,
                filterable: true,
                tag: props.tag,
                onUpdateValue: (v) => {
                  selectValue.value = v
                },
                onChange: handleChange,
                onBlur: handleChange
              },
              null
            )
          : props.value
      )
  }
})

export default ShowOrSelect
